/**
 * Created by   :王书中
 * Created time :2017/5/03/19:38
 * File explain :施小包账户-充值
 */

require.config({
  baseUrl: "../../libs",
  paths: {
    jquery: ["jquery/jquery-1.11.3"],
    layer: ["layer/layer"],
    zui: ["zui/js/zui"],
    boot: ["bootstrap-3.3.7-dist/js/bootstrap"],
    bootTable: ["bootstrap-table-dist/dist/js/bootstrap-table"],
    bootTableCN: ["bootstrap-table-dist/dist/locale/bootstrap-table-zh-CN"],
    config:["../common/js/common-config"],
    page:["../common/js/qhpager"]
  }
});
require(["jquery"], function () {
  require(["bootTable"], function () {
    require(["layer","zui","boot","bootTableCN","config","page"], operationCodeFun)
  });
});
//代码容器

function operationCodeFun() {
  "use strict";
  const QHConfig = $("body").data("config");//配置文件常量
  var userCode=window.sessionStorage.getItem("userCode");
  var manageInfo=JSON.parse(window.sessionStorage.getItem("manageInfo"));
  var billInfo=QHConfig.getSearchDataFun();//账单跳转
  var operName = JSON.parse(window.sessionStorage.getItem("detail")).realName;//操作员name，主子账号
  var bankInfo = null;//存放选择的银行的信息
  var needData = null;//充值需要的参数
  //从账单进来付款
  if(billInfo.amount){
    $(".recharge-amount-content").val(billInfo.amount.slice(0,billInfo.amount.length-3));
    $(".recharge-land-btn").addClass("recharge-land-orange");
  }
  //layer框架配置
  layer.config({
    path:"../../libs/layer/"
  });
  //页面渲染，渲染可供选择的更多银行
  rederMoreBank();//选择其他银行

  //金额输入事件
  $(".recharge-amount-content").on("input",function(){
    checkTotalPrice(this);
  }).on("blur",function(){
    moneyBlur(this);
  });
  //登录到网上银行按钮
  $(".recharge-land-btn").on("click",loginBankFun);
  //选择其他银行后下一步按钮
  $(".next-step").on("click",clickOtherBankFun);
  //返回我的账户
  $(".back-account").on("click",function() {
    parent.parent.layer.closeAll();
  });

  /*to do 其他函数*/
  //选择更多银行
  function rederMoreBank() {
    $.ajax(tokenAjax({
      type : "get",
      url : QHConfig.url.selectChannelList + "PC",
      success : function(data) {
        var _data = data.data;
        renderBankInfo(_data);//渲染银行卡信息
      }
    }));
  }
  //生成银行卡
  function renderBankInfo(_data) {
    var oHtml = "";//代码容器
    //信息有误，不渲染
    if(!_data) {
      return;
    }
    for(var i=0;i<_data.length;i++) {
      //默认为建行
      if(_data[i].type == 0) {
        if(_data[i].payType == "B2B_NB") {
          renderHtmlCard(_data[i]);
          oHtml += `<div class="choice-bank active" data-type="${_data[i].type}" data-code="${_data[i].channelCode}" data-payType="${_data[i].payType}">
              <div class="choice-bank-detail">
                <div class="choice-bank-choose-active"></div>
                <img class="choice-bank-logo" src="${_data[i].logoPc}" alt="">
                <div class="choice-corporate-card active" data-type="${_data[i].type}"></div>
              </div>
            </div>`;
        }else {
          if($(".e-bank-name").html() == "") {
            renderHtmlCard(_data[i]);
          }
          oHtml += `<div class="choice-bank" data-type="${_data[i].type}" data-code="${_data[i].channelCode}" data-payType="${_data[i].payType}">
              <div class="choice-bank-detail">
                <div class="choice-bank-choose"></div>
                <img class="choice-bank-logo" src="${_data[i].logoPc}" alt="">
                <div class="choice-corporate-card" data-type="${_data[i].type}"></div>
              </div>
            </div>`;
        }
      }

    }
    $(".choice-bank-name").append(oHtml);
    //选择其他银行鼠标点击事件
    $(".choice-bank-name .choice-bank").on("click",otherBankFun);
  }
  //页面默认的合作银行
  function renderHtmlCard(data) {
    var str = `<div class="e-bank">
      <div class="e-bank-detail active" data-type="${data.type}" data-code="${data.channelCode}" data-payType="${data.payType}">
        <div class="e-bank-choose-active"></div>
        <img class="e-bank-logo" src="${data.logoPc}" alt="">
        ${data.type == 0?"<div class='corporate-card' data-type="+data.type+"></div>":""}
      </div>
    </div>`;
    $(".e-bank-name").append(str);
  }
 function moneyBlur(obj){
    var str = obj.value.toString();
    if(str == "") {
      obj.value = "";
      $(".recharge-land").children("button").removeClass("recharge-land-orange");
      return;
    }
    var length = str.length;
    var index = str.indexOf(".");
    var overNum = length - index;//加小数点后有几位；
    if(str == "") {
      return;
    }
    if(index == -1&&str.length < 14&&str.length > 0) {
      obj.value = str.substring(0,13) + ".00";
    }else if(overNum == 1) {
      obj.value = str + "00";
    }else if(overNum == 2) {
      obj.value = str + "0";
    }else if(overNum == 3) {
      obj.value = str;
    }
    $(".recharge-land").children("button").addClass("recharge-land-orange");
  };
  //最多15位，加上小数点和小数点后两位
  function checkTotalPrice(obj) {
    obj.value = obj.value.replace(/[^\d.]/g,"");//只能数字和小数点
    obj.value = obj.value.replace(/^\./g,"");//验证第一个字符是数字而不是小数点、
    obj.value = obj.value.replace(/\.{2,}/g,".");//只保留一个，清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,"$1$2.$3");//两位小数
    var str = obj.value.toString();

    if(str.indexOf(".") == -1&&str.length > 13) {
      obj.value = Number(str.substring(0,13));
    }
  }
  //选择其他银行点击事件回调
  function otherBankFun(){
    $(this).addClass("active").find(".choice-bank-choose").removeClass("choice-bank-choose")
      .addClass("choice-bank-choose-active").parents(".choice-bank").siblings(".choice-bank").removeClass("active").find(".choice-bank-choose-active")
      .removeClass("choice-bank-choose-active").addClass("choice-bank-choose");
  }

  function loginBankFun(){
    var money = $(".recharge-amount-content").val();//输入金额
    var returnUrl = getRootPath() + "/operat-result/operat-result.html";//成功回调地址
    var publicBank = $(".e-bank .corporate-card").attr("data-type");//判断银行卡类型

    $(".money-notice").text("金额不能为空");//默认
    if(money == "") {
      $(".recharge-amount-content")[0].focus();
      $(".money-notice").show();//显示提示
      return;
    }else {
      $(".money-notice").hide();//隐藏提示
    };
    if(publicBank == 0&&money<10) {
      $(".recharge-amount-content").val("");
      $(".recharge-amount-content")[0].focus();
      $(".money-notice").text("金额不准低于10元最小限额，请重新输入").show();//显示提示
      return;
    }
    //选则了其他银行卡
    if(bankInfo != null) {
      needData = {
        amount:money,
        channel:bankInfo.channel,
        payType:bankInfo.payType,
        operName:operName,
        returnUrl:returnUrl
      };
    }else {//默认为建行的
      needData = {
        amount:money,
        channel:$(".e-bank-detail").attr("data-code"),
        payType:$(".e-bank-detail").attr("data-payType"),
        operName:operName,
        returnUrl:returnUrl
      };
    }
    changeRecharge(needData);
  }
  //选择其他银行后下一步点击回调
  function clickOtherBankFun(){
    var choosedBank = $(".choice-bank-name>.active");

    bankInfo = {
      channel:choosedBank.attr("data-code"),
      payType:choosedBank.attr("data-payType"),
      type:choosedBank.attr("data-type"),
      logo:choosedBank.find("img").attr("src")
    };
    $(".e-bank-detail").find("img").attr("src",bankInfo.logo);//替换图片
    $(".e-bank-detail").find(".corporate-card").attr("data-type",bankInfo.type);
  }
  /*
   * 获取根目录地址
   * @author wangshuzhong
   * @Date   2017/5/12
   * */
  function getRootPath(){
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);

    return (localhostPaht + projectName);
  }
  //提交充值ajax
  function changeRecharge(needData){
    //layer.msg("跳转到网银支付页面");
    $.ajax(tokenAjax({
      type:"post",
      url:QHConfig.url.recharge,
      data:JSON.stringify(needData),
      contentType:"application/json",
      success:function(data) {
        if(data.status == 200) {
          //$(".e-bank-container").hide();
          //$(".wait-container").removeClass("hide");
          layerRecharge();
          window.open(data.data.url);
        }
      }
    }))
  }
  function layerRecharge(){
    layer.open({
      title: ["充值","background:#009CFF;color:#fff;font-size:16px"],
      shade: 0.5,
      move:false,
      closeBtn:1,
      resize:false,
      scrollbar:false,
      type: 2,
      area: ['700px', '220px'],
      content: "../common/cmn-project-recharge.html",
      success:function(layero,index) {
        var closeBtn=$(".layui-layer-setwin a");//layer的title关闭按钮
        var sure=layer.getChildFrame(".cmn-save-btn",index);//确定
        var cancel=layer.getChildFrame(".cmn-cancel-btn",index);//取消

        closeBtn.css({"background":"#009CFF","color":"#fff","font-size":"16px","margin-top":"-5px"});//关闭按钮样式
        closeBtn.text("X");
        cancel.on("click",function() {
          layer.closeAll();
          layerNew("../recharge-fail/recharge-fail.html");
        });
        sure.on("click",function() {
          layer.closeAll();
          layerNew("../recharge-success/recharge-success.html");
        });
      }
    });
  }
  /*
   * 弹出新页面
   * @params url,收货详情页面地址
   * @author wangshuzhong
   * @Date   2017/5/11
   * */
  function layerNew(url) {
    layer.open({
      title: false,
      shade: 0.8,
      move:false,
      closeBtn:0,
      resize:false,
      scrollbar:false,
      type: 2,
      area: ['100%', '100%'],
      content: url,
      end:function(){
        window.location.reload();
      }
    })
  };
}